package com.bds.btcdc.web.filter;

import com.bds.btcdc.web.action.BaseAction;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.CookieUtils;
import com.bds.btcdc.web.utils.DESUtil;
import com.bds.btcdc.web.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.Set;

/**
 * Created by DongChenchen on 2018/4/17 0017
 */
public class RedisSessionInterceptor extends BaseAction implements HandlerInterceptor {
	private Set<String> writeUrls;

	public RedisSessionInterceptor() {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getServletPath();
		// 判断是否是本地开发环境不需要验证,线上环境注意要把这个去掉
		if (Const.IS_SKIP) {
			return true;
		}

		if (writeUrls != null) {
			for (String url : writeUrls) {
				if (path.matches(url)) {
					return true;
				}
			}
		}
		Boolean needLogin = false;// 是否需要重新登录
		// 从客户端cookies读取加密user_id
		try {
			Cookie cookie = CookieUtils.getCookieByName(request, Const.COOKIES_USER_KEY);
			if (cookie != null) {
				String token = cookie.getValue();
				Charset CHARSET = Charset.forName("utf-8");
				String user_id = DESUtil.decrypt(token, CHARSET, Const.DESKEY);
				// 从redis读取登录信息
				// String userSessionStr =
				// RedisUtil.getInstance().hash().hget(Const.REDIS_SESSION_HASH_KEY,
				// email);
				String userSessionStr = RedisUtil.getInstance().strings().get(user_id);
				// UserSession user = (UserSession)
				// SerializationUtils.deserialize(Base64.decodeBase64(userSessionStr));
				if (StringUtils.isBlank(userSessionStr)) {
					needLogin = true;
				}
			} else {
				needLogin = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			needLogin = true;
		}

		if (needLogin) { // 重新登录
			response.sendRedirect(Const.PORTAL_DOMAIN + "/portal/login.html");
			return false;
		} else {
			return true;
		}

	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {

	}

	public Set<String> getWriteUrls() {
		return writeUrls;
	}

	public void setWriteUrls(Set<String> writeUrls) {
		this.writeUrls = writeUrls;
	}

}
